import api from './api.js'; //封装微信/wx-app的request

function request(url, data = {}, method = 'GET', contentType = 'application/json') {
	return new Promise(function(resolve, reject) {
		let fullUrl = `${api.localIP}${url}`;
		let appCode = uni.getStorageSync('appCode') || 'GAT-LIFE';
		// console.log(method, contentType, fullUrl, 'aaa');
		// console.log('入参', data);
		uni.showLoading({
			title: '加载中'
		});
		uni.request({
			url: fullUrl,
			data: data,
			method: method,
			header: {
				'Content-Type': contentType,
				Authorization: uni.getStorageSync('AUTHORIZATION'),
				// "role_type":wx.getStorageSync("role_type"),// 1 业主 2员工
				appCode: appCode //物业 GAT  业主 GAT-LIFE
			},
			success: (res) => {
				// console.log('success');
				uni.hideLoading(); // console.log(res,"res")

				if (res.statusCode == 200) {
					//需要跟后端确定这些错误码以及登录状态
					// console.log('返回', fullUrl, res.data);

					if (res.data.code == '00007') {
						goLogin();
					}

					resolve(res.data);
				} else if (res.statusCode == 911) {
					goLogin();
					reject(res.errMsg);
				} else {
					reject(res.errMsg);
				}
			},
			fail: (err) => {
				uni.hideLoading();
				reject(err);
				console.log('failed');
			}
		});
	});
}

function get(url, data = {}, contentType) {
	return request(url, data, 'GET', contentType);
}

function post(url, data = {}, contentType) {
	return request(url, data, 'POST', contentType);
}

function goLogin() {
	uni.showToast({
		title: '登录已过期，请重新登录',
		icon: 'none'
	});
	setTimeout(() => {
		uni.clearStorageSync();
		if (uni.getStorageSync('weixin') == 2) {
			jWeixin.miniProgram.navigateTo({
				url: "/pages/login/login"
			})
		} else {
			uni.reLaunch({
				url: '/pages/login/login'
			});
		}
	}, 2000);
}

function getNetWork() {
	uni.getNetworkType({
		success(res) {
			//res.networkType none 无网络
			uni.showModal({
				title: '当前网络',
				content: res.networkType,
				showCancel: false,
				confirmText: '我知道了',
				confirmColor: '#FFA000',

				success(res) {
					if (res.confirm) {}
				}
			});
			return res.networkType;
		}
	});
} //封装存储（注意：这里的存储过程是异步的）

function setStorage(key, val) {
	return new Promise((resolve, reject) => {
		uni.setStorage({
			key: key,
			data: val,
			success: () => {
				resolve(true);
			},
			fail: () => {
				reject(false);
			}
		});
	});
} //封装获取存储

function getStorage(key) {
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: 'key',
			success: (res) => {
				resolve(res.data);
			},
			fail: () => {
				reject('获取存储失败');
			}
		});
	});
}

function replaceImgUrl(e) {
	//单个替换图片地址--纯图片地址
	let index = String(e).indexOf('/group');
	let result = e; // if(index > -1){
	// 	let url = e.substring(0,index)
	// 	result = e.replace(url,api.imgUrl)
	// }

	return result;
} //获取用户当前状态

function getUserStatus() {
	let certificationState = uni.getStorageSync('certificationState');
	let authState = uni.getStorageSync('authState');
	let result = true;

	if (!uni.getStorageSync('AUTHORIZATION')) {
		uni.showModal({
			title: '',
			content: '您未登录，请先登录',
			showCancel: true,
			cancelText: '取消',
			cancelColor: '#999',
			confirmText: '去登录',
			confirmColor: '#FFA000',

			success(res) {
				if (res.confirm) {
					if (uni.getStorageSync('weixin') == 2) {
						jWeixin.miniProgram.navigateTo({
							url: "/pages/login/login"
						})
					} else {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}
				} else if (res.cancel) {}
			}
		});
		result = false;
	}

	if (authState == 2) {
		result = false;

		if (certificationState == 0) {
			uni.showToast({
				title: '您提交的认证信息正在审核，请耐心等待',
				icon: 'none'
			});
		} else if (certificationState == -1) {
			uni.showModal({
				title: '',
				content: '抱歉，您提交的认证信息审核不通过，请重新认证',
				showCancel: true,
				cancelText: '取消',
				cancelColor: '#999',
				confirmText: '去认证',
				confirmColor: '#FFA000',

				success(res) {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/ownerCertification/ownerCertification'
						});
					}
				}
			});
		} else if (certificationState == null || certificationState == 'null' || certificationState == '-2') {
			uni.showModal({
				title: '',
				content: '您未认证，请先认证',
				showCancel: true,
				cancelText: '取消',
				cancelColor: '#999',
				confirmText: '去认证',
				confirmColor: '#FFA000',

				success(res) {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/ownerCertification/ownerCertification'
						});
					} else if (res.cancel) {}
				}
			});
		}
	}

	return result;
}
/**
 * 获取URL中某个字符串字段
 * gup('id', 'https://shbjy.hzxh.gov.cn?id=80&type=activity')
 * //===> bHViYW5zb7W7DJI=
 */

function gup(name, url) {
	if (!url) url = location.href;
	name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
	var regexS = '[\\?&]' + name + '=([^&#]*)';
	var regex = new RegExp(regexS);
	var results = regex.exec(url);
	return results == null ? null : results[1];
}

module.exports = {
	request,
	get,
	post,
	setStorage,
	getStorage,
	replaceImgUrl,
	getUserStatus,
	gup
};
